package com.talkyun.utils.store;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;

public class DiskStore {
    private Logger logger = LoggerFactory.getLogger(DiskStore.class);

    private String file;

    public DiskStore(String file) {
        this.file = file;
        // logger.info("store {} -> {}", file, getLocalFile());
    }

    public String load() {
        File file = new File(this.getLocalFile());
        try {
            return this.load(file);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public void store(String text) throws IOException {
        File file = new File(this.getLocalFile());
        if (!file.exists()) {
            file.getParentFile().mkdirs();
            if (!file.createNewFile()) {
                System.err.println("Can't create " + file.getPath());
            }
        }
        if (!file.exists()) {
            System.err.println("Not found: " + file.getPath());
        }

        this.writeFile(file, text);
    }

    private String load(File file) throws IOException {
        if (!file.exists()) {
            return null;
        }

        // System.out.println(" read file " + file.getAbsolutePath());
        return this.readFile(file);
    }

    private String getLocalFile() {
        String path = System.getProperty("user.home");
        path += File.separator + ".openx";
        path += File.separator + file;
        return path.toLowerCase();
    }

    private void writeFile(File file, String json) throws IOException {
        FileOutputStream fos = new FileOutputStream(file);
        try {
            fos.write(json.getBytes("utf-8"));
        } finally {
            this.close(fos);
        }
    }

    private String readFile(File file) throws IOException {
        FileInputStream fis = new FileInputStream(file);
        StringBuilder sb = new StringBuilder(4096);

        try {
            byte[] buf = new byte[1024];
            for (int num = fis.read(buf); num != -1; num = fis.read(buf)) {
                sb.append(new String(buf, 0, num, "utf-8"));
            }
        } finally {
            this.close(fis);
        }
        return sb.toString();
    }

    private void close(Closeable cls) {
        try {
            if (cls != null) {
                cls.close();
            }
        } catch (IOException e) {
            // ignore
            e.printStackTrace(System.err);
        }
    }
}